package org.vs.handler.responsibilitychain.vote;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Component;
import org.vs.annotation.CheckBalance;
import org.vs.contract.VoteContract;
import org.vs.domain.model.TOption;
import org.vs.domain.vo.ProgressVO;
import org.vs.handler.responsibilitychain.BaseResponsibilityChainHandler;
import org.vs.mapper.TOptionMapper;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Component
public class VotePublishOptionHandler extends BaseResponsibilityChainHandler {
    @Resource
    private TOptionMapper optionMapper;

    @Resource
    private VotePublishUserHandler votePublishUserHandler;

    @CheckBalance
    @Override
    protected boolean customerHandler(Object obj) {
        try {
            VotePublishHandlerEO votePublishHandlerEO = (VotePublishHandlerEO) obj;

            votePublishHandlerEO.setCount(votePublishHandlerEO.getCount() + 1);
            setHandler(votePublishUserHandler);
            setMessage(votePublishHandlerEO.getHashcode(), JSON.toJSONString(ProgressVO
                    .builder()
                    .progress((100 / voteCount) * votePublishHandlerEO.getCount())
                    .info("完成选项信息写入")
                    .build()));

            List<TOption> options = optionMapper.selectList(new QueryWrapper<TOption>()
                    .eq("vote_id", votePublishHandlerEO.getVote().getVoteId()));
            List<VoteContract.Option> voteOptions = new ArrayList<>();
            options.stream().forEach(v -> {
                voteOptions.add(new VoteContract.Option(
                        BigInteger.valueOf(v.getOptionId()),
                        v.getName(),
                        v.getImage(),
                        v.getDescription()));
            });
            votePublishHandlerEO.getVoteContract().setOptions(voteOptions).send();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
